<!--
 * @Author: WLang
 * @LastEditors: WLang
 * @Description: 
 * @Date: 2023-07-04 15:25:29
 * @LastEditTime: 2023-07-19 18:15:04
 * @FilePath: \myblog\src\views\EditorView.vue
-->
<template>
  <el-card class="blog-editor">
    <div class="blog-editor--title">
      <h3>文章标题</h3>
      <el-input ref="title" v-model="title" placeholder="请输入内容"></el-input>
    </div>
    <div class="blog-editor--content">
      <h3>内容编辑</h3>
      <div id="blog-editor-textarea">
      </div>
    </div>
    <div class="blog-editor--tags">
      <h3 class="blog-tags--title">设置分类</h3>
      <el-radio-group v-model="column" >
        <el-radio-button :label="item.id" v-for="item in columns.list" :key="item.id">{{item.name}}</el-radio-button>
      </el-radio-group>
    </div>
    <div class="blog-editor--buton">
      <el-button type="primary" @click="submitEditor">上传<i class="el-icon-upload el-icon--right"></i></el-button>
      <el-button type="primary" icon="el-icon-delete" @click="cancelEditor">取消</el-button>
    </div>
  </el-card>
</template>

<script>
import wangEditor from 'wangeditor'
export default {
  data () {
    return {
      editor: null,
      title: '',
      content: '',
      columns: {},
      column: ''
    };
  },
  props: {
    columnId: {
      type: String
    }
  },
  created() {
    this.getColumns();
    if (this.columnId)
    {
      this.column = this.columnId
      return 
    }
  },
  mounted () {
    const editor = new wangEditor(`#blog-editor-textarea`)
    editor.config.onchange = (newHtml) => {
      this.content = newHtml  
    }
    this.editor = editor
    this.editor.config.uploadImgServer = process.env.VUE_APP_FILE_UPLOAD_PATH
    this.editor.config.uploadImgMaxSize = 5 * 1024 * 1024 // 5M
    this.editor.config.uploadImgAccept = ['jpg', 'jpeg', 'png', 'gif', 'bmp']
    this.editor.config.uploadImgMaxLength = 5
    this.editor.config.uploadFileName = 'file'
    this.editor.config.uploadImgHeaders = {
      'Authorization': `Bearer ${this.$store.state.token}`,
    }
    editor.create()
  },
  methods: {
       //获得img标签
       getImg(content) {
      return content.match(/(?<=(img[^>]*src="))[^"]*/g)
    },
    //去除<img>标签 获得content html
    getContent (content) {
      let deArray = content.match(/<img.*?(?:>|\/>)/gi);
      if (deArray  != null && deArray  != undefined) {
        for (let vm of deArray)
        {
          return content.replace(vm, "");
        }
      }
      return content
    },
    // 获取分类
    async getColumns () {
      try {
        let columns = await this.$api({type: 'columns'})
        this.columns = columns
      }
      catch(err)
      {
        console.log(err)
      }
    },
    submitEditor () {
      if (!this.validateEditor()) {
        return
      }
      this.postEditorData()
    },
    cancelEditor () {
      this.editor.txt.clear()
    },
    validateEditor () {
      if (this.title.trim().length === 0) {
        this.$notify.error({
          title: '错误',
          message: '请填写标题'
        })
        this.$refs.title.focus()
        return false
      }
      if (this.content.trim().length === 0) {
        this.$notify.error({
          title: '错误',
          message: '内容不能为空'
        })
        return false
      }
      return true
    },
    async postEditorData () {
      console.log('提交数据')
      try {
        this.$api({
          type: 'postArticle', data: {
            title: this.title,
            content: this.getContent(this.content),
            //TODO 封装column
            column: this.column,
            cover: this.getImg(this.content)?.[0]
          }
        })
        this.$notify.success({
          title: '成功',
          message: '文章提交成功'
        })
        this.$router.push('/index')
      } catch (err) {
        this.$message.error({
          title: '错误',
          message: '提交失败'
        })
      }

    }
  },

  beforeDestroy () {
    // 调用销毁 API 对当前编辑器实例进行销毁
    this.editor.destroy()
    this.editor = null
  }
};
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="scss">
  .blog-editor h3{
    line-height: 40px;
  }
  .blog-editor--title {
    margin-bottom: 10px;
  }

  .blog-editor--content {
    margin-bottom: 10px;
  }

  .blog-editor--tags {
    margin-bottom: 10px;
  }

  .blog-editor--buton {
    width: 100%;
    text-align: center;
    .el-button {
      padding: 10px 40px;
    }
  }
</style>
